//
//  SearchController.m
//  Otaku
//
//  Created by lanou3g on 16/5/14.
//  Copyright © 2016年 Liuwx. All rights reserved.
//

#import "SearchController.h"
#import "SearchCell.h"
#import "SearchModel.h"
#import "SearchWenViewController.h"
@interface SearchController ()<UISearchBarDelegate>
//设置搜索框
@property (nonatomic,strong) UISearchBar *searchBar;
//webView展示详情页面
@property (nonatomic, strong) UIWebView *newsDetaView;


//数据源数组
@property (nonatomic, strong) NSMutableArray *searchArray;
@property (nonatomic, strong) NSString *string;
@end

@implementation SearchController
//懒加载数据源的数组
- (NSMutableArray *)searchArray {
    
    if (!_searchArray) {
        _searchArray = [[NSMutableArray alloc] init];
    }
    return _searchArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"搜索";
self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)];

    self.searchBar.barStyle = UIBarStyleDefault;
    self.searchBar.placeholder = @"请输入搜索内容";
    self.searchBar.delegate = self;
    self.tableView.tableHeaderView = self.searchBar;
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([SearchCell class]) bundle:nil] forCellReuseIdentifier:@"cell"];
    
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    self.string = searchBar.text;
    [self searchResulData];
    [self.searchArray removeAllObjects];
    [self.searchBar resignFirstResponder];
}

//数据请求
- (void)searchResulData {
    //字符转URL的编码

    NSString *contentStr =  [self.string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
    NSString *str = [NSString stringWithFormat:@"http://ic.snssdk.com/api/2/essay/content/search_all/?keyword=%@&screen_width=720&iid=4240101979&device_id=3468889146&ac=wifi&channel=xiaomi&aid=7&app_name=joke_essay&version_code=500&device_platform=android&device_type=MI+2S&os_api=21&os_version=5.0.2&uuid=863077027303431&openudid=f15b00ad8c7c42dc&csrfmiddlewaretoken=undefined",contentStr];

    
    NSURL *url = [NSURL URLWithString:str];
   
   [LWXNetWorkRequestManager requestURL:url Method:LWX_GET Params:nil Result:^(NSData *data, NSURLResponse *response, NSError *error) {
 
       if (data) {
           NSMutableDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
           NSDictionary *data = jsonDict[@"data"];
           for (NSDictionary *itemDict in data[@"text"]) {
               SearchModel *model = [SearchModel new];
               [model setValuesForKeysWithDictionary:itemDict];
               [self.searchArray addObject:model];
           }
       dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
                       
        });
       
       }else {
           
           UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:@"没有要查询的内容" preferredStyle:UIAlertControllerStyleAlert];
           [alertC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
           
           [self.navigationController pushViewController:alertC animated:YES];
      
       }
       
   }];
        
  
    
        }
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    SearchWenViewController *webVC = [[SearchWenViewController alloc] init];
    SearchModel *model = self.searchArray[indexPath.row];
    webVC.string = model.share_url;
    
    [self.navigationController pushViewController:webVC animated:YES];
    
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    return self.searchArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SearchCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    cell.model = self.searchArray[indexPath.row];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    SearchModel *model = self.searchArray[indexPath.row];
    return model.cellHeight;

}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
